package com.bobo.netty.service;

import com.bobo.netty.client.ChatClient;
import com.bobo.netty.server.websocketchat.WebSocketChatServer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;
@Service
public class WebSocketNettyServerImpl implements ImServer, ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private WebSocketChatServer webSocketChatServer;
    @Resource
    private ChatClient chatClient;
    /**
     * 标识服务是否开启
     */
    private AtomicBoolean started = new AtomicBoolean(false);
    @Override
    public void start() {
        try {
            System.out.println("开启socket");
            if(started.compareAndSet(false,true)){
                System.out.println("重启socket");
                webSocketChatServer.open();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        System.out.println("关闭socket");
        if(started.get()){
            try {
                webSocketChatServer.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        System.out.println("12345678");
        start();
    }
}
